package com.taxi.driver.module.order.list;

import com.qianxx.utils.RxUtil;
import com.taxi.driver.R;
import com.taxi.driver.common.BasePresenter;
import com.taxi.driver.data.order.OrderRepository;
import com.taxi.driver.data.user.UserRepository;
import com.taxi.driver.module.vo.OrderSummaryVO;

import javax.inject.Inject;

/**
 * 功能描述：
 */
public class OrderListPresenter extends BasePresenter implements OrderListContract.Presenter {

    private final OrderListContract.View mView;
    private final OrderRepository mOrderRepository;
    private final UserRepository mUserRepository;

    private int nowPage = 1;

    @Inject
    public OrderListPresenter(OrderListContract.View view, OrderRepository orderRepository, UserRepository userRepository) {
        mView = view;
        mOrderRepository = orderRepository;
        mUserRepository = userRepository;
    }

    @Override
    public void refresh() {
        mSubscriptions.add(
                mOrderRepository.reqOrderList(1)
                        .flatMapIterable(entities -> entities)
                        .map(OrderSummaryVO::createFrom)
                        .toList()
                        .compose(RxUtil.applySchedulers())
                        .doAfterTerminate(() -> nowPage = 2)
                        .subscribe(mView::setList,
                                ex -> showNetworkError(ex, R.string.network_error, mView)));
    }

    @Override
    public void loadMore() {
        mSubscriptions.add(
                mOrderRepository.reqOrderList(nowPage)
                        .flatMapIterable(entities -> entities)
                        .map(OrderSummaryVO::createFrom)
                        .toList()
                        .compose(RxUtil.applySchedulers())
                        .doAfterTerminate(() -> nowPage++)
                        .subscribe(mView::appendList,
                                ex -> showNetworkError(ex, R.string.network_error, mView)));
    }

    @Override
    public void reqOrderDetail(String orderUuid) {
        mSubscriptions.add(
                mOrderRepository.reqOrderDetail(orderUuid, true)
                        .compose(RxUtil.applySchedulers())
                        .doOnSubscribe(() -> mView.showLoadingView(true))
                        .doAfterTerminate(mView::hideLoadingView)
                        .subscribe(entity -> {
                            if (entity.isOrderOngoing()) { //跳转进行中订单
                                mView.openOrderOngoing(entity.uuid);
                            } else { //跳转订单详情
                                mView.openOrderDetail(entity.uuid,entity.subStatus);
                            }
                        }, ex -> {
                            showNetworkError(ex, R.string.network_error, mView, mUserRepository);
                            mView.reassign();
                        }));
    }

    @Override
    public int driverType() {
        return mUserRepository.getDriverType();
    }
}
